<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/6/25
 * Time: 20:11
 */

namespace Common\Model;


class ProductModel
{
    private $detailCacheKey = 'wxshop_product_detail_';

    /**
     * 获取产品详情
     * @param $productId
     * @return bool
     */
    public function detail($productId){
        if(empty($productId)) return false;
        
        if(S($this->detailCacheKey.$productId)){
            $detail = S($this->detailCacheKey.$productId);
            
            if($detail){
                $detail = array_map('unserialize',$detail);
            }
            
            return $detail;
        } else {
            return $this->_detail($productId);
        }
    }

    private function _detail($productId){
        if(empty($productId)) return false;

        $detail = M('project')->where(array('id'=>$productId))->field(true)->find();

        if(empty($detail)) return false;

        if($detail['attr']){
            $detail['attr'] = unserialize($detail['attr']);
            
            $attrPrice = array();
            foreach ($detail['attr'] as $val){
                $attrPrice[] = $val['price'];
            }
            
            $attrPrice = array_unique($attrPrice);
            
            if(count($attrPrice)==1){
                $detail['range_price'] = $attrPrice[0];
            } else {
                $detail['range_price'] = min($attrPrice).'~'.max($attrPrice);//区间价格
            }
        } else {
            $detail['range_price'] = $detail['price'];
        }
        
        S($this->detailCacheKey.$productId,array_map('serialize',$detail));
        
        return $detail;
    }

    /**
     * 清除缓存
     * @param $productId
     */
    public function clearCache($productId){
        $this->_detail($productId);
    }
}